package com.chenfan.magic.resolver;

import com.chenfan.magic.core.IdcEngineEntry;
import com.chenfan.magic.core.MagicLogPublisher;
import com.chenfan.magic.entity.TTLDetailModel;
import com.chenfan.magic.utils.Charsets;
import com.chenfan.magic.utils.IDKit;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * @author lm
 * Freemarker 解析器
 *
 */
@Component
@AllArgsConstructor
public class FreemarkerResolver implements __IResolver {

    public static final String TYPE_CODE = "freemarker";

    @Override
    public String resolve(Map<String, Object> idcRuntimePool, String templateContent, Map<String, Object> paramMap) {
        TTLDetailModel ttlDetailModel = new TTLDetailModel();
        ttlDetailModel.start();
        String result = "";
        String uuid = IDKit.fastUUID();
        Configuration cfg = new Configuration();
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("idc-resolver-template-freemarker-" + uuid, templateContent);
        cfg.setTemplateLoader(stringLoader);
        try {
            Template template = cfg.getTemplate("idc-resolver-template-freemarker-" + uuid, Charsets.UTF_8_NAME);
            StringWriter writer = new StringWriter();
            try {
                template.process(paramMap, writer);
                result = writer.toString();
                MagicLogPublisher.publishResolverEvent(TYPE_CODE, templateContent, result, paramMap, ttlDetailModel.end().getTtl() + "");
            } catch (TemplateException e) {
                e.printStackTrace();
                MagicLogPublisher.publishResolverEvent(TYPE_CODE, templateContent, result, paramMap, ttlDetailModel.end().getTtl() + "", e);
                IdcEngineEntry.throwException(idcRuntimePool, null, e);
            }
        } catch (IOException e) {
            e.printStackTrace();
            MagicLogPublisher.publishResolverEvent(TYPE_CODE, templateContent, result, paramMap, ttlDetailModel.end().getTtl() + "", e);
            IdcEngineEntry.throwException(idcRuntimePool, null, e);
        }
        return result;
    }
}
